package com.wman.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.wman.R;
import com.wman.sheep.common.utils.DensityUtil;

import androidx.annotation.Nullable;

/**
 * @ProjectName: wman
 * @Package: com.wman.view
 * @ClassName: CustomView
 * @Description: java类作用描述
 * @Author: wman
 * @CreateDate: 2019/11/6 12:02
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/11/6 12:02
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class CameraView extends View {

    private Bitmap mBitmap;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Camera mCamera = new Camera();

    public CameraView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        mBitmap = getAvatar(400);
        mCamera.rotateX(30);
        //skia规定的Z是-8（英寸） == 72像素，会有兼容问题  -8 = -8*72
        mCamera.setLocation(0, 0, DensityUtil.getZForCamera());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        canvas.translate(100 + mBitmap.getWidth() / 2, 100 + mBitmap.getHeight() / 2);
        canvas.rotate(-20);
        canvas.clipRect(-mBitmap.getWidth(), -mBitmap.getWidth(), mBitmap.getWidth(), 0);
        canvas.rotate(20);
        canvas.translate(-(100 + mBitmap.getWidth() / 2), -(100 + mBitmap.getHeight() / 2));
        canvas.drawBitmap(mBitmap, 100, 100, mPaint);
        canvas.restore();

        canvas.translate(100 + mBitmap.getWidth() / 2, 100 + mBitmap.getHeight() / 2);
        canvas.rotate(-20);
        mCamera.applyToCanvas(canvas);
        canvas.clipRect(-mBitmap.getWidth(), 0, mBitmap.getWidth(), mBitmap.getWidth());
        canvas.rotate(20);
        canvas.translate(-(100 + mBitmap.getWidth() / 2), -(100 + mBitmap.getHeight() / 2));
        canvas.drawBitmap(mBitmap, 100, 100, mPaint);
    }

    private Bitmap getAvatar(int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), R.mipmap.icon_avatar, options);
        options.inJustDecodeBounds = false;
        options.inDensity = options.outWidth;
        options.inTargetDensity = width;
        return BitmapFactory.decodeResource(getResources(), R.mipmap.icon_avatar, options);
    }
}
